import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:stock_check/common/dao/DataResult.dart';
import 'package:stock_check/common/dao/TasksDao.dart';
import 'package:stock_check/common/dao/UserDao.dart';
import 'package:stock_check/common/model/taskItem.dart';
import 'package:stock_check/common/model/app.dart';
import 'package:stock_check/common/model/taskItemDetail.dart';
import 'package:stock_check/common/model/uploadTaskBean.dart';
import 'package:stock_check/common/redux/CheckDevicesReducer.dart';
import 'package:stock_check/common/redux/reduxStore.dart';
import 'package:stock_check/common/utils/NavigatorUtils.dart';
import 'package:stock_check/widget/CommonsWidget.dart';
import 'package:stock_check/widget/GradientButton.dart';
import 'package:stock_check/widget/MyScaffold.dart';
import 'package:stock_check/widget/renderTaskItemWidget.dart';

/// 盘点清单
class CheckList extends StatefulWidget {
  final TaskItem item;

  const CheckList({Key key, @required this.item}) : super(key: key);

  @override
  _CheckListState createState() => _CheckListState();
}

class _CheckListState extends State<CheckList> {
  ScrollController controller = new ScrollController();
  List<TaskDetailItem> list = new List();
  int userId;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _initTaskList();
  }

  _initTaskList() async {
    list = await TasksDao.findTaskListByTaskID(widget.item.id);
    DataResult result = await UserDao.getUserInfoLocal();
    userId = result.data.id;
    setState(() {});
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return StoreBuilder<StockState>(builder: (context, store) {
      App appInfo = store.state.appInfo;
      bool online = appInfo.netWork.index != 2;
      return MyScaffold(
          store: store,
          title: Text("盘点清单"),
          noLeading: true,
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 0.0, horizontal: 5.0),
            child: Column(
              children: <Widget>[
                ListTile(
                  dense: true,
                  contentPadding: EdgeInsets.all(10.0),
                  leading: Row(
                    children: <Widget>[
                      Icon(
                        Icons.assignment,
                        color: Colors.blue,
                      ),
                      Text("  ${widget.item.taskName}",
                          style: TextStyle(
                              color: Theme.of(context).accentColor,
                              fontSize: 15.0))
                    ],
                  ),
                ),
                Divider(
                  height: .0,
                ),
                Expanded(
                    child: ListView.builder(
                        itemCount: list.length,
                        itemBuilder: (context, index) {
                          if (index != list.length - 1)
                            return RenderTaskItemWidget(
                              item: list[index],
                            );
                          else
                            return _noMore();
                        })),
                Padding(
                  padding: EdgeInsets.only(top: 30.0),
                ),
                Container(
                  width: double.infinity,
                  height: 80.0,
                  child: Column(
                    children: <Widget>[
                      Flex(
                        direction: Axis.horizontal,
                        children: <Widget>[
                          Expanded(
                            flex: 10,
                            child:  GradientButton(
                              height: 45.0,
                              colors: [Colors.purple, Colors.redAccent],
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Icon(
                                    Icons.cloud_upload,
                                    color: Colors.white,
                                  ),
                                  Text(
                                    online ? " 上传已确认结果" : " 离线",
                                    style: TextStyle(color: Colors.white),
                                  ),
                                ],
                              ),
                              onTap: online ? ()=>_submit(store): null
                            ),
                          ),
                          Spacer(
                            flex: 1,
                          ),
                          Expanded(
                            flex: 10,
                            child: GradientButton(
                              height: 45.0,
                              colors: [Colors.blue, Colors.green],
                              child:Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Icon(
                                    Icons.camera,
                                    color: Colors.white,
                                  ),
                                  Text(
                                    " 开始盘点",
                                    style: TextStyle(color: Colors.white),
                                  ),
                                ],
                              ),
                              onTap: () {
                                NavigatorUtils.goTaskScanPage(
                                    context, list, userId);
                              },
                            ),
                          )
                        ],
                      )
                    ],
                  ),
                )
              ],
            ),
          ));
    });
  }

  _submit (store) async {
    int sum = 0;
    List<UploadTaskBean> needUpload = new List();
    for (int i = 0; i < list.length; i++) {
      if (list[i].status == 2) {
        sum++;
        list[i].position =
        list[i].position.isEmpty ? '空' : list[i].position;
        needUpload.add(
            UploadTaskBean.copy(list[i]));
      }
    }
    String msg = '是否确认提交数据?';
    if (sum < list.length) {
      msg = '还有${list.length - sum}项资产没有确认,是否确认提交数据?';
    }
    bool flag =
    await CommonsWidget.confirmDialog(
        context, msg);
    if (flag == true) {
      bool res =
      await TasksDao.uploadTaskData(
          userId, needUpload);
      if (res == true) {
        //删除该条记录
        List<TaskItem> tasks =
            store.state.worksInfo.tasks;
        tasks.removeWhere((f) {
          return f.id == list[0].taskId;
        });
        store.dispatch(UpdateTasksAction(
            tasks: tasks));
        Navigator.pop(context);
      }
    }
  }

  Widget _noMore() {
    return Container(
      padding: EdgeInsets.only(bottom: 50.0, top: 10.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            "没有更多....",
            style: TextStyle(color: Colors.grey),
          )
        ],
      ),
    );
  }
}
